﻿<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="CPAIS.Web.Default" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>CPAIS</title>

    <!-- For extJS -->
    <link href="Components/ext-4.2.0-gpl/resources/css/ext-all-gray.css" rel="stylesheet" />
    <script src="Components/ext-4.2.0-gpl/ext-all.js"></script>
    <script src="Components/ext-4.2.0-gpl/Notification.js"></script>
    <script src="Components/ext-4.2.0-gpl/TabCloseMenu.js"></script>

    <!-- For Plupload -->
    <link href="Components/jquery-ui-1.8.20/themes/base/jquery-ui.css" rel="stylesheet" />
    <link href="Components/plupload-1.5.7/js/jquery.ui.plupload/css/jquery.ui.plupload.css" rel="stylesheet" />
    <script src="Components/jquery-ui-1.8.20/jquery-1.7.1.min.js"></script>
    <script src="Components/jquery-ui-1.8.20/jquery-ui-1.8.20.min.js"></script>
    <script src="Components/plupload-1.5.7/js/plupload.js"></script>
    <script src="Components/plupload-1.5.7/js/plupload.gears.js"></script>
    <script src="Components/plupload-1.5.7/js/plupload.silverlight.js"></script>
    <script src="Components/plupload-1.5.7/js/plupload.flash.js"></script>
    <script src="Components/plupload-1.5.7/js/plupload.browserplus.js"></script>
    <script src="Components/plupload-1.5.7/js/plupload.html4.js"></script>
    <script src="Components/plupload-1.5.7/js/plupload.html5.js"></script>
    <script src="Components/plupload-1.5.7/js/jquery.ui.plupload/jquery.ui.plupload.js"></script>

    <!-- For CPAIS Application -->
    <link href="Content/cpais-default.css" rel="stylesheet" />
    <link href="Content/cpais-icon-all.css" rel="stylesheet" />
    <link href="Content/cpais-overview.css" rel="stylesheet" />
    <link href="Content/cpais-others.css" rel="stylesheet" />
    <script type="text/javascript">

        // Called when Ext startup
        Ext.onReady(function () {

            // 1. Create viewport
            createViewport();

            // 2. Open overview tab
            openStartTab('overview');

            // 3. Hide loading mask
            document.getElementById('loadingMask').style.display = 'none';
        });

        // Show a message window in bottom-right
        function showMsg(title, content) {
            Ext.create('widget.uxNotification', {
                position: 'br',
                closable: true,
                title: title,
                width: 200,
                autoCloseDelay: 5000,
                html: '<div style="margin: 10px; color: #882299">' + content + '</div>'
            }).show();
        }

        // Open the video page
        function openIntroducingVideo() {
            window.open("IntroducingVideo/CPAIS.html");
        }

        // Create viewport: north, west, center and south parts
        function createViewport() {

            var northPanel = Ext.create('Ext.panel.Panel', {
                region: 'north',
                height: 60,
                border: false,
                html: '<div class="header"><div class="navigation"><a href="Default.aspx">Home</a>|<a href="javascript:openIntroducingVideo();">Introducing Video</a>|<a href="mailto:junw.mao@gmail.com">Contact</a></div></div>'
            });

            var southPanel = Ext.create('Ext.panel.Panel', {
                region: 'south',
                height: 25,
                border: false,
                html: '<div class="footer">College of Biomedical Engineering & Instrument Science (2013.05)</div>'
            });

            var menuTreeStore = Ext.create('Ext.data.TreeStore', {
                autoLoad: true,
                proxy: {
                    type: 'ajax',
                    url: 'Servlet.ashx?action=GetMenuTreeNodes'
                },
                listeners: {
                    beforeload: function () {
                        if (menuTreePanel) {
                            menuTreePanel.body.mask('Loading...');
                        }
                        var refreshTool = Ext.getCmp('refreshMenuTree');
                        if (refreshTool) {
                            refreshTool.disable();
                        }
                    },
                    load: function () {
                        if (menuTreePanel) {
                            menuTreePanel.body.unmask();
                        }
                        var refreshTool = Ext.getCmp('refreshMenuTree');
                        if (refreshTool) {
                            refreshTool.enable();
                        }
                    }
                }
            });

            var menuTreePanel = Ext.create('Ext.tree.Panel', {
                padding: 3,
                useArrows: true,
                rootVisible: false,
                store: menuTreeStore,
                listeners: {
                    itemClick: function (view, record) {
                        var data = record.data;
                        if (data.leaf) {
                            if (data.id == 'upload' || data.id == 'overview') {
                                openStartTab(data.id);
                            }
                            else {
                                openLogTab(data.id);
                            }
                        }
                        else if (data.expanded) {
                            this.collapseNode(record);
                        }
                        else {
                            this.expandNode(record);
                        }
                    }
                }
            });

            var westPanel = Ext.create('Ext.panel.Panel', {
                region: 'west',
                width: 230,
                border: true,
                margin: '5 0 0 0',
                collapsible: true,
                split: true,
                layout: 'fit',
                title: 'Navigation',
                tools: [{
                    id: 'refreshMenuTree',
                    type: 'refresh',
                    tooltip: 'Refresh form server',
                    handler: function () {
                        menuTreeStore.reload();
                    }
                }],
                items: [menuTreePanel]
            });

            var mainTabs = Ext.create('Ext.tab.Panel', {
                id: 'mainTabs',
                region: 'center',
                layout: 'fit',
                padiing: 0,
                border: true,
                margin: '5 0 0 0',
                plugins: Ext.create('Ext.ux.TabCloseMenu'),
                listeners: {
                    remove: function (container, component) {
                        var id = component.id;
                        if (id == 'overview' || id == 'upload') {
                            return;
                        }
                        // Request to remove log
                        Ext.Ajax.request({
                            url: 'Servlet.ashx',
                            params: {
                                action: 'RemoveLog',
                                logName: id
                            },
                            success: function (response) {
                                if (response.responseText == 'OK') {
                                    showMsg('Message', 'Event log "' + id + '" has been removed.');
                                }
                                else if (response.responseText == 'NotExisted') {
                                    showMsg('Message', 'Event log "' + id + '" is not existed, may be removed by another page of current session.');
                                }
                            }
                        });
                    }
                }
            });

            Ext.create('Ext.container.Viewport', {
                layout: 'border',
                renderTo: Ext.getBody(),
                items: [northPanel, southPanel, westPanel, mainTabs]
            });
        }

        // Open start tab, including '#overview', '#upload'
        function openStartTab(id) {

            var mainTabs = Ext.getCmp("mainTabs");
            var tab = mainTabs.getComponent(id);
            if (!tab) {
                var iconCls, title, url;
                if (id == 'overview') {
                    iconCls = 'o-icon-overview';
                    title = 'Overview';
                    url = 'Overview.html';
                }
                else {
                    iconCls = 'o-icon-upload';
                    title = 'Upload';
                    url = 'Upload.html';
                }
                tab = Ext.create('Ext.panel.Panel', {
                    id: id,
                    title: title,
                    iconCls: iconCls,
                    closable: true,
                    autoScroll: true,
                    layout: 'fit',
                    bodyPadding: 0,
                    padding: 0,
                    loader: {
                        url: url,
                        loadMask: true,
                        autoLoad: true,
                        scripts: true
                    }
                });
                mainTabs.add(tab);
            }
            mainTabs.setActiveTab(tab);
        }

        // Open log tab, before open it, we will request loading progress
        function openLogTab(logName) {

            var mainTabs = Ext.getCmp("mainTabs");
            var tab = mainTabs.getComponent(logName);
            if (!tab) {
                // Request to load log
                Ext.Ajax.request({
                    url: 'Servlet.ashx',
                    params: {
                        action: 'LoadLog',
                        logName: logName
                    },
                    success: function (response) {
                        var resText = response.responseText;
                        if (resText == 'Existed') {
                            addLogTab(mainTabs, logName);
                        }
                        else if (resText == 'Started') {
                            requestLoadLog(mainTabs, logName);
                        }
                    }
                });
            }
            mainTabs.setActiveTab(tab);
        }

        // Request to load log and show loading progress
        function requestLoadLog(mainTabs, logName) {
            var loadMsgBox, loadTask;
            loadMsgBox = Ext.MessageBox.show({
                title: 'Loading event log',
                iconCls: 'o-icon-xml',
                closable: false,
                modal: true,
                autoDestroy: true,
                buttons: Ext.MessageBox.CANCEL,
                fn: function () {
                    // Cancel the loading task
                    Ext.TaskManager.stop(loadTask);
                    Ext.Ajax.request({
                        url: 'Servlet.ashx',
                        params: {
                            action: 'CancelLoadLog',
                            logName: logName
                        }
                    });
                }
            });
            var msgRenderer = function (msg) {
                return '<br/><br/>&nbsp;&nbsp;&nbsp;&nbsp;<span style="font-size: 12px; color: #553399;">' + msg + '</span>';
            };
            loadTask = {
                run: function () {
                    Ext.Ajax.request({
                        url: 'Servlet.ashx',
                        params: {
                            action: 'QueryLoadLogProgress',
                            logName: logName
                        },
                        success: function (response) {
                            var data = eval('(' + response.responseText + ')');
                            if (data) {
                                if (data.state == 'Completed') {
                                    Ext.TaskManager.stop(loadTask);
                                    loadMsgBox.hide();
                                    addLogTab(mainTabs, logName);
                                }
                                else if (data.state == 'Failed') {
                                    Ext.TaskManager.stop(loadTask);
                                    loadMsgBox.update('Failed: ' + msgRenderer(data.msg));
                                }
                                else { // May be 'Ready', 'Updating'
                                    loadMsgBox.update(msgRenderer(data.msg));
                                }
                            }
                        }
                    });
                },
                interval: 500 // 500ms
            };
            loadMsgBox.update(msgRenderer('Initializing...'));
            Ext.TaskManager.start(loadTask);
        }

        // Add a new log tab
        function addLogTab(mainTabs, logName) {

            var addLogPanelsFinished = false;
            var loadGridFinished = false;
            var logTabMaskRemoved = false;
            var logTab = Ext.create('Ext.tab.Panel', {
                id: logName,
                title: logName,
                closable: true,
                autoScroll: true,
                loadMask: true,
                tabPosition: 'left',
                iconCls: 'o-icon-xml',
                layout: 'fit',
                bodyPadding: 0,
                padding: 0,
                bbar: [{
                    xtype: 'button',
                    html: '<span class="o-button-text">LDA Analysis</span>',
                    scale: 'medium',
                    iconCls: 'o-icon-analysis',
                    iconAlign: 'left',
                    handler: function () {
                        var ldaTab = logTab.getComponent('ldaTab');
                        if (ldaTab) {
                            logTab.setActiveTab(ldaTab);
                        }
                        else {
                            doLDAAnalysis(logTab, logName);
                        }
                    }
                }, {
                    xtype: 'button',
                    html: '<span class="o-button-text">CPM Analysis</span>',
                    scale: 'medium',
                    iconCls: 'o-icon-analysis',
                    iconAlign: 'left',
                    handler: function () {
                        var cpmTab = logTab.getComponent('cpmTab');
                        if (cpmTab) {
                            logTab.setActiveTab(cpmTab);
                        }
                        else {
                            doCPMAnalysis(logTab, logName);
                        }
                    }
                }, {
                    xtype: 'button',
                    html: '<span class="o-button-text">HLDA Analysis</span>',
                    scale: 'medium',
                    iconCls: 'o-icon-analysis',
                    iconAlign: 'left',
                    handler: function () {
                        var cpmTab = logTab.getComponent('hldaTab');
                        if (cpmTab) {
                            logTab.setActiveTab(cpmTab);
                        }
                        else {
                            doHLDAAnalysis(logTab, logName);
                        }
                    }
                },
                 {
                     xtype: 'button',
                     html: '<span class="o-button-text">HDP Analysis</span>',
                     scale: 'medium',
                     iconCls: 'o-icon-analysis',
                     iconAlign: 'left',
                     handler: function () {
                         var hdpTab = logTab.getComponent('hdpTab');
                         if (hdpTab) {
                             logTab.setActiveTab(hdpTab);
                         }
                         else {
                             doHDPAnalysis(logTab, logName);
                         }
                     }
                 },
                {
                    xtype: 'button',
                    html: '<span class="o-button-text">CPM Analysis Speed Test</span>',
                    scale: 'medium',
                    iconCls: 'o-icon-analysis',
                    iconAlign: 'left',
                    handler: function () {
                        //  Test Analysis Speed
                        var tasTab = logTab.getComponent('tasTab');
                        if (tasTab) {
                            logTab.setActiveTab(tasTab);
                        }
                        else {
                            doTestAnalysisSpeed(logTab, logName);
                        }
                    }
                }]
            });
            mainTabs.add(logTab);
            mainTabs.setActiveTab(logTab);
            logTab.body.mask('Loading log summary...');

            // Request to get log summary
            Ext.Ajax.request({
                url: 'Servlet.ashx',
                params: {
                    action: 'GetLogSummary',
                    logName: logName
                },
                success: function (response) {
                    var result = eval('(' + response.responseText + ')');
                    // Create summary form
                    var count = result.data.length;
                    var fields = new Array(count);
                    for (var i = 0; i < count; i++) {
                        fields[i] = Ext.create('Ext.form.field.Display', {
                            fieldLabel: result.data[i][0],
                            value: result.data[i][1]
                        });
                    }
                    var summaryForm = Ext.create('Ext.form.Panel', {
                        bodyPadding: 10,
                        width: 1000,
                        collapsible: true,
                        fieldDefaults: {
                            labelAlign: 'left',
                            labelWidth: 120
                        },
                        margin: '0 0 15 0',
                        title: 'Summary',
                        items: fields
                    });

                    // Create trace grid
                    var pageSize = 50;
                    var traceStore = Ext.create('Ext.data.Store', {
                        storeId: 'traceStore',
                        autoLoad: {
                            start: 0, limit: pageSize
                        },
                        proxy: {
                            type: 'ajax',
                            url: 'servlet.ashx?action=GetTraceData&logName=' + logName,
                            reader: {
                                type: 'json',
                                root: 'items',
                                totalProperty: 'total'
                            }
                        },
                        pageSize: pageSize,
                        fields: [
                            { name: 'pid', type: 'string' },
                            { name: 'sex', type: 'string' },
                            { name: 'birthday', type: 'string' },
                            { name: 'department', type: 'string' },
                            { name: 'admit', type: 'string' },
                            { name: 'discharge', type: 'string' },
                            { name: 'cost', type: 'float' },
                            { name: 'los', type: 'int' },
                            { name: 'actions', type: 'int' },
                            { name: 'obervs', type: 'int' },
                            { name: 'diagnoses', type: 'int' }
                        ],
                        listeners: {
                            load: function () {
                                loadGridFinished = true;
                                if (loadGridFinished && addLogPanelsFinished && !logTabMaskRemoved) {
                                    logTab.body.unmask();
                                    logTabMaskRemoved = true;
                                }
                            }
                        }
                    });
                    var traceGridPanel = Ext.create('Ext.grid.Panel', {
                        title: 'Patient Traces',
                        store: traceStore,
                        margin: '0 0 10 0',
                        width: 1000,
                        maxHeight: 450,
                        dockedItems: [{
                            xtype: 'pagingtoolbar',
                            store: traceStore,
                            dock: 'bottom',
                            displayInfo: true
                        }],
                        loadMask: true,
                        columns: [
                            { xtype: 'rownumberer', align: 'center' },
                            { text: 'PID', dataIndex: 'pid', width: 80, align: 'center' },
                            { text: 'Sex', dataIndex: 'sex', width: 50, align: 'center' },
                            { text: 'Birthday', dataIndex: 'birthday', width: 80, align: 'center' },
                            { text: 'Department', dataIndex: 'department', width: 165, align: 'left' },
                            { text: 'Admit', dataIndex: 'admit', width: 120, align: 'center' },
                            { text: 'Discharge', dataIndex: 'discharge', width: 120, align: 'center' },
                            { text: 'Cost', dataIndex: 'cost', width: 70, align: 'center' },
                            { text: 'LOS', dataIndex: 'los', width: 50, align: 'center' },
                            {
                                text: 'Actions',
                                dataIndex: 'actions',
                                width: 60,
                                align: 'center',
                                renderer: function (value, metaData, record) {
                                    return '<a class="o-grid-cell-text" href="javascript:onActionCellClick(\'' + record.data.pid +
                                        '\', \'' + logName + '\');">' + value + '</a>';
                                }
                            },
                            {
                                text: 'Obervations',
                                dataIndex: 'obervs',
                                width: 80,
                                align: 'center',
                                renderer: function (value, metaData, record) {
                                    return '<a class="o-grid-cell-text" href="javascript:onObservationCellClick(\'' + record.data.pid +
                                        '\', \'' + logName + '\');">' + value + '</a>';
                                }
                            },
                            {
                                text: 'Diagnoses',
                                dataIndex: 'diagnoses',
                                width: 70,
                                align: 'center',
                                renderer: function (value, metaData, record) {
                                    return '<a class="o-grid-cell-text" href="javascript:onDiagnosisCellClick(\'' + record.data.pid +
                                        '\', \'' + logName + '\');">' + value + '</a>';
                                }
                            }
                        ]
                    });

                    // Create a tab panel to show log result
                    var logResultPanel = Ext.create('Ext.panel.Panel', {
                        title: 'Summary',
                        closable: false,
                        autoScroll: true,
                        loadMask: true,
                        bodyPadding: 10,
                        iconCls: 'o-icon-summary',
                        items: [summaryForm, traceGridPanel]
                    });

                    // Add the log result panel to log tab
                    addLogPanelsFinished = true;
                    logTab.add(logResultPanel);
                    if (loadGridFinished && addLogPanelsFinished) {
                        logTab.body.unmask();
                        logTabMaskRemoved = true;
                    }
                }
            });
        }

        // Show action detail grid window
        function onActionCellClick(pid, logName) {
            Ext.create('Ext.window.Window', {
                title: 'Detail of actions for patient ' + pid,
                width: 400,
                height: 300,
                modal: true,
                iconCls: 'o-icon-action',
                resizable: true,
                layout: 'fit',
                items: {
                    xtype: 'grid',
                    border: false,
                    loadMask: true,
                    columns: [
                        { xtype: 'rownumberer', width: 30, align: 'center' },
                        { text: 'Timestamp', dataIndex: 'timestamp', width: 120, align: 'center' },
                        { text: 'Day', dataIndex: 'day', width: 50, align: 'center' },
                        { text: 'Action', dataIndex: 'action', width: 170, align: 'left' }
                    ],
                    store: Ext.create('Ext.data.Store', {
                        autoLoad: true,
                        fields: ['timestamp', 'day', 'action'],
                        proxy: {
                            type: 'ajax',
                            url: 'servlet.ashx?action=GetActionDetails&logName=' + logName + '&pid=' + pid
                        }
                    })
                }
            }).show();
        }

        // Show observation detail grid window
        function onObservationCellClick(pid, logName) {
            Ext.create('Ext.window.Window', {
                title: 'Detail of observations for patient ' + pid,
                width: 400,
                height: 300,
                modal: true,
                iconCls: 'o-icon-observ',
                resizable: true,
                layout: 'fit',
                items: {
                    xtype: 'grid',
                    border: false,
                    loadMask: true,
                    columns: [
                        { xtype: 'rownumberer', width: 30, align: 'center' },
                        { text: 'Timestamp', dataIndex: 'timestamp', width: 120, align: 'center' },
                        { text: 'Day', dataIndex: 'day', width: 50, align: 'center' },
                        { text: 'Observation', dataIndex: 'observ', width: 170, align: 'left' }
                    ],
                    store: Ext.create('Ext.data.Store', {
                        autoLoad: true,
                        fields: ['timestamp', 'day', 'observ'],
                        proxy: {
                            type: 'ajax',
                            url: 'servlet.ashx?action=GetObservationDetails&logName=' + logName + '&pid=' + pid
                        }
                    })
                }
            }).show();
        }

        // Show diagnosis detail grid window
        function onDiagnosisCellClick(pid, logName) {
            Ext.create('Ext.window.Window', {
                title: 'Detail of diagnoses for patient ' + pid,
                width: 400,
                height: 300,
                modal: true,
                iconCls: 'o-icon-diagnosis',
                resizable: true,
                layout: 'fit',
                items: {
                    xtype: 'grid',
                    border: false,
                    loadMask: true,
                    columns: [
                        { xtype: 'rownumberer', width: 30, align: 'center' },
                        { text: 'Diagnosis', dataIndex: 'diagnosis', width: 340, align: 'left' }
                    ],
                    store: Ext.create('Ext.data.ArrayStore', {
                        autoLoad: true,
                        fields: ['diagnosis'],
                        proxy: {
                            type: 'ajax',
                            url: 'servlet.ashx?action=GetDiagnosisDetails&logName=' + logName + '&pid=' + pid
                        }
                    })
                }
            }).show();
        }

        // Do LDA analysis
        function doLDAAnalysis(tabPanel, logName) {
            var fieldK = Ext.create('Ext.form.field.Number', {
                anchor: '100%',
                name: 'k',
                fieldLabel: 'K',
                value: 3,
                maxValue: 10,
                minValue: 1,
                step: 1,
                keyNavEnabled: true,
                mouseWheelEnabled: true,
                allowBlank: false,
                allowDecimal: false
            });
            var fieldAlpha = Ext.create('Ext.form.field.Number', {
                anchor: '100%',
                name: 'alpha',
                fieldLabel: 'Alpha',
                value: 0.1,
                maxValue: 1,
                minValue: 0.01,
                step: 0.01,
                keyNavEnabled: true,
                mouseWheelEnabled: true,
                allowBlank: false
            });
            var fieldBeta = Ext.create('Ext.form.field.Number', {
                anchor: '100%',
                name: 'beta',
                fieldLabel: 'Beta',
                value: 0.05,
                maxValue: 1,
                minValue: 0.01,
                step: 0.005,
                keyNavEnabled: true,
                mouseWheelEnabled: true,
                allowBlank: false
            });
            var fieldIterations = Ext.create('Ext.form.field.Number', {
                anchor: '100%',
                name: 'iterations',
                fieldLabel: 'Iterations',
                value: 1000,
                maxValue: 100000,
                minValue: 500,
                step: 50,
                keyNavEnabled: true,
                mouseWheelEnabled: true,
                allowBlank: false,
                allowDecimal: false
            });
            var progressBar = Ext.create('Ext.ProgressBar', {
                width: 160
            });
            var task;
            var startButton = Ext.create('Ext.button.Button', {
                text: 'Start',
                handler: function () {
                    if (!(fieldK.isValid() && fieldAlpha.isValid() && fieldBeta.isValid() && fieldIterations.isValid())) {
                        alert('Invalid parameters');
                        return;
                    }
                    fieldK.disable();
                    fieldAlpha.disable();
                    fieldBeta.disable();
                    fieldIterations.disable();
                    this.disable();

                    Ext.Ajax.request({
                        url: 'Servlet.ashx',
                        params: {
                            action: 'LDAAnalysis',
                            logName: logName,
                            k: fieldK.getValue(),
                            alpha: fieldAlpha.getValue(),
                            beta: fieldBeta.getValue(),
                            iterations: fieldIterations.getValue()
                        },
                        success: function (response) {
                            task = {
                                run: function () {
                                    Ext.Ajax.request({
                                        url: 'Servlet.ashx',
                                        params: {
                                            action: 'QueryLDAAnalysisProgress',
                                            logName: logName
                                        },
                                        success: function (response) {
                                            var data = eval('(' + response.responseText + ')');
                                            if (data) {
                                                if (data.state == 'Completed') {
                                                    Ext.TaskManager.stop(task);
                                                    operateWnd.close();
                                                    addLDAAnalysisTab(tabPanel, logName);
                                                }
                                                else if (data.state == 'Failed') {
                                                    Ext.TaskManager.stop(task);
                                                    progressBar.updateProgress(0.0, data.msg);
                                                }
                                                else { // May be 'Ready', 'Updating'
                                                    progressBar.updateProgress(data.progress, data.msg);
                                                }
                                            }
                                        }
                                    });
                                },
                                interval: 500 // 500ms
                            };
                            Ext.TaskManager.start(task);
                        }
                    });
                }
            });
            var cancelButton = Ext.create('Ext.button.Button', {
                text: 'cancel',
                handler: function () {
                    operateWnd.close();
                    if (startButton.disabled) {
                        Ext.TaskManager.stop(task);
                        Ext.Ajax.request({
                            url: 'Servlet.ashx',
                            params: {
                                action: 'CancelLDAAnalysis',
                                logName: logName
                            }
                        });
                    }
                }
            });
            var operateWnd = Ext.create('Ext.window.Window', {
                title: 'LDA Analysis',
                width: 350,
                height: 220,
                layout: 'fit',
                modal: true,
                iconCls: 'o-icon-analysis-small',
                resizable: false,
                closable: false,
                items: {
                    xtype: 'form',
                    bodyPadding: 15,
                    fieldDefaults: {
                        labelAlign: 'left',
                        labelWidth: 60
                    },
                    items: [fieldK, fieldAlpha, fieldBeta, fieldIterations],
                    buttons: [progressBar, cancelButton, startButton]
                }
            }).show();
        }

        // Add an lda analysis tab
        function addLDAAnalysisTab(tabPanel, logName) {

            var loadDocTopicGridFinished = false;
            var loadTopicsFinished = false;
            var addLDAPanelsFinished = true;
            var ldaTabMaskRemoved = false;
            var ldaResultTab = Ext.create('Ext.panel.Panel', {
                title: 'LDA Analysis',
                id: 'ldaTab',
                closable: true,
                autoScroll: true,
                loadMask: true,
                bodyPadding: 10,
                iconCls: 'o-icon-analysis-small'
            });
            tabPanel.add(ldaResultTab);
            tabPanel.setActiveTab(ldaResultTab);
            ldaResultTab.body.mask('Loading LDA analysis result...');
            var checkLoadingFinished = function () {
                if (loadDocTopicGridFinished && loadTopicsFinished && addLDAPanelsFinished && !ldaTabMaskRemoved) {
                    ldaResultTab.body.unmask();
                    ldaTabMaskRemoved = true;
                }
            }

            Ext.Ajax.request({
                url: 'Servlet.ashx',
                params: {
                    action: 'GetLDAAnalysisSummary',
                    logName: logName
                },
                success: function (response) {
                    var result = eval('(' + response.responseText + ')');
                    // Create summary form
                    var count = result.data.length;
                    var fields = new Array(count);
                    for (var i = 0; i < count; i++) {
                        fields[i] = Ext.create('Ext.form.field.Display', {
                            fieldLabel: result.data[i][0],
                            value: result.data[i][1]
                        });
                    }
                    var summaryForm = Ext.create('Ext.form.Panel', {
                        bodyPadding: 10,
                        width: 1000,
                        collapsible: true,
                        fieldDefaults: {
                            labelAlign: 'left',
                            labelWidth: 120
                        },
                        margin: '0 0 15 0',
                        title: 'Summary',
                        items: fields
                    });

                    // Create document-topic association panel (HBox)
                    var pageSize = 20;
                    var docStore = Ext.create('Ext.data.Store', {
                        storeId: 'docStore',
                        autoLoad: {
                            start: 0,
                            limit: pageSize
                        },
                        proxy: {
                            type: 'ajax',
                            url: 'servlet.ashx?action=GetLDADocData&logName=' + logName,
                            reader: {
                                type: 'json',
                                root: 'items',
                                totalProperty: 'total'
                            }
                        },
                        pageSize: pageSize,
                        fields: [
                            { name: 'pid', type: 'string' }
                        ],
                        listeners: {
                            load: function () {
                                loadDocTopicGridFinished = true;
                                checkLoadingFinished();
                            }
                        }
                    });
                    var docGridPanel = Ext.create('Ext.grid.Panel', {
                        store: docStore,
                        width: 390,
                        margin: '0 10 0 0',
                        maxHeight: 450,
                        dockedItems: [{
                            xtype: 'pagingtoolbar',
                            store: docStore,
                            dock: 'bottom',
                            displayInfo: true
                        }],
                        loadMask: true,
                        columns: [
                            { xtype: 'rownumberer', align: 'center' },
                            { text: 'PID', dataIndex: 'pid', width: 345, align: 'center' }
                        ],
                        listeners: {
                            select: function (view, record, index, eOpts) {
                                onLDADocRowSelect(record.data.pid, logName);
                            }
                        }
                    });
                    var docTopicStore = Ext.create('Ext.data.Store', {
                        storeId: 'ldaDocTopicStore_' + logName,
                        autoLoad: false,
                        fields: [
                            { name: 'topicNo', type: 'string' },
                            { name: 'probability', type: 'float' }
                        ]
                    });
                    var docTopicChart = Ext.create('Ext.chart.Chart', {
                        xtype: 'chart',
                        width: 500,
                        height: 350,
                        animate: true,
                        store: docTopicStore,
                        shadow: true,
                        legend: {
                            position: 'right'
                        },
                        insetPadding: 20,
                        theme: 'Base:gradients',
                        series: [{
                            type: 'pie',
                            angleField: 'probability',
                            showInLegend: true,
                            tips: {
                                trackMouse: true,
                                width: 140,
                                height: 28,
                                renderer: function (storeItem, item) {
                                    // calculate and display percentage on hover
                                    var total = 0;
                                    docTopicStore.each(function (rec) {
                                        total += rec.get('probability');
                                    });
                                    this.setTitle(storeItem.get('topicNo') + ': ' + Math.round(storeItem.get('probability') / total * 100) + '%');
                                }
                            },
                            highlight: {
                                segment: {
                                    margin: 20
                                }
                            },
                            label: {
                                field: 'topicNo',
                                display: 'rotate',
                                contrast: true,
                                font: '18px Arial'
                            }
                        }]
                    });
                    var docHBox = Ext.create('Ext.panel.Panel', {
                        width: 1000,
                        height: 300,
                        collapsible: true,
                        margin: '0 0 10 0',
                        title: 'Patient Trace - CP Pattern Association (Click the grid row to view probabilitie of topics)',
                        layout: {
                            type: 'hbox',
                            align: 'stretch'
                        },
                        items: [docGridPanel, docTopicChart]
                    });
                    var topicVBox = Ext.create('Ext.panel.Panel', {
                        width: 1000,
                        autoScroll: true,
                        collapsible: true,
                        margins: '0 0 10 0',
                        title: 'CP Patterns',
                        bodyPadding: 5,
                        layout: {
                            type: 'vbox',
                            align: 'stretch'
                        }
                    });
                    Ext.Ajax.request({
                        type: 'ajax',
                        url: 'Servlet.ashx',
                        params: {
                            action: 'GetLDATopicData',
                            logName: logName
                        },
                        success: function (response) {
                            var result = eval('(' + response.responseText + ')');
                            var length = result.items.length;
                            for (var i = 0; i < length; i++) {
                                var store = Ext.create('Ext.data.Store', {
                                    fields: [
                                        { name: 'name', type: 'string' },
                                        { name: 'prob', type: 'float' }
                                    ],
                                    data: result.items[i].actions
                                });
                                var grid = Ext.create('Ext.grid.Panel', {
                                    store: store,
                                    maxHeight: 300,
                                    columns: [
                                        { xtype: 'rownumberer', width: 30, align: 'center' },
                                        { text: 'Action Name', dataIndex: 'name', width: 390, align: 'left' },
                                        { xtype: 'numbercolumn', text: 'Probability', dataIndex: 'prob', align: 'center', format: '0.0000' }
                                    ]
                                });
                                topicVBox.add(Ext.create('Ext.panel.Panel', {
                                    title: 'CP Pattern ' + (i + 1).toString() + ' - Probability: ' + result.items[i].prob.toString(),
                                    margins: '0 0 10 0',
                                    collapsible: true,
                                    items: [grid]
                                }));
                            }
                            loadTopicsFinished = true;
                            checkLoadingFinished();
                        }
                    });

                    // Add the lda result panels to lda tab
                    addLDAPanelsFinished = true;
                    ldaResultTab.add(summaryForm);
                    ldaResultTab.add(docHBox);
                    ldaResultTab.add(topicVBox);
                    checkLoadingFinished();
                }
            });
        }

        // Show document-topic association
        function onLDADocRowSelect(pid, logName) {
            var store = Ext.data.StoreManager.lookup('ldaDocTopicStore_' + logName);
            if (store) {
                store.setProxy({
                    type: 'ajax',
                    url: 'Servlet.ashx?action=GetLDADocTopicProbability&logName=' + logName + '&pid=' + pid
                });
                store.reload();
            }
        };

        // Do CPM analysis
        function doCPMAnalysis(tabPanel, logName) {
            var fieldK = Ext.create('Ext.form.field.Number', {
                anchor: '100%',
                name: 'k',
                fieldLabel: 'K',
                value: 3,
                maxValue: 10,
                minValue: 1,
                step: 1,
                keyNavEnabled: true,
                mouseWheelEnabled: true,
                allowBlank: false,
                allowDecimal: false
            });
            var fieldAlpha = Ext.create('Ext.form.field.Number', {
                anchor: '100%',
                name: 'alpha',
                fieldLabel: 'Alpha',
                value: 0.1,
                maxValue: 1,
                minValue: 0.01,
                step: 0.01,
                keyNavEnabled: true,
                mouseWheelEnabled: true,
                allowBlank: false
            });
            var fieldBeta = Ext.create('Ext.form.field.Number', {
                anchor: '100%',
                name: 'beta',
                fieldLabel: 'Beta',
                value: 0.01,
                maxValue: 1,
                minValue: 0.01,
                step: 0.005,
                keyNavEnabled: true,
                mouseWheelEnabled: true,
                allowBlank: false
            });
            var fieldGamma = Ext.create('Ext.form.field.Number', {
                anchor: '100%',
                name: 'gamma',
                fieldLabel: 'Gamma',
                value: 0.01,
                maxValue: 1,
                minValue: 0.01,
                step: 0.005,
                keyNavEnabled: true,
                mouseWheelEnabled: true,
                allowBlank: false
            });
            var fieldIterations = Ext.create('Ext.form.field.Number', {
                anchor: '100%',
                name: 'iterations',
                fieldLabel: 'Iterations',
                value: 1000,
                maxValue: 100000,
                minValue: 500,
                step: 50,
                keyNavEnabled: true,
                mouseWheelEnabled: true,
                allowBlank: false,
                allowDecimal: false
            });
            var progressBar = Ext.create('Ext.ProgressBar', {
                width: 160
            });
            var task;
            var startButton = Ext.create('Ext.button.Button', {
                text: 'Start',
                handler: function () {
                    if (!(fieldK.isValid() && fieldAlpha.isValid() && fieldBeta.isValid() && fieldIterations.isValid())) {
                        alert('Invalid parameters');
                        return;
                    }
                    fieldK.disable();
                    fieldAlpha.disable();
                    fieldBeta.disable();
                    fieldGamma.disable();
                    fieldIterations.disable();
                    this.disable();

                    Ext.Ajax.request({
                        url: 'Servlet.ashx',
                        params: {
                            action: 'CPMAnalysis',
                            logName: logName,
                            k: fieldK.getValue(),
                            alpha: fieldAlpha.getValue(),
                            beta: fieldBeta.getValue(),
                            gamma: fieldGamma.getValue(),
                            iterations: fieldIterations.getValue()
                        },
                        success: function (response) {
                            task = {
                                run: function () {
                                    Ext.Ajax.request({
                                        url: 'Servlet.ashx',
                                        params: {
                                            action: 'QueryCPMAnalysisProgress',
                                            logName: logName
                                        },
                                        success: function (response) {
                                            var data = eval('(' + response.responseText + ')');
                                            if (data) {
                                                if (data.state == 'Completed') {
                                                    Ext.TaskManager.stop(task);
                                                    operateWnd.close();
                                                    addCPMAnalysisTab(tabPanel, logName);
                                                }
                                                else if (data.state == 'Failed') {
                                                    Ext.TaskManager.stop(task);
                                                    progressBar.updateProgress(0.0, data.msg);
                                                }
                                                else { // May be 'Ready', 'Updating'
                                                    progressBar.updateProgress(data.progress, data.msg);
                                                }
                                            }
                                        }
                                    });
                                },
                                interval: 500 // 500ms
                            };
                            Ext.TaskManager.start(task);
                        }
                    });
                }
            });
            var cancelButton = Ext.create('Ext.button.Button', {
                text: 'cancel',
                handler: function () {
                    operateWnd.close();
                    if (startButton.disabled) {
                        Ext.TaskManager.stop(task);
                        Ext.Ajax.request({
                            url: 'Servlet.ashx',
                            params: {
                                action: 'CancelCPMAnalysis',
                                logName: logName
                            }
                        });
                    }
                }
            });
            var operateWnd = Ext.create('Ext.window.Window', {
                title: 'CPM Analysis',
                width: 350,
                height: 250,
                layout: 'fit',
                modal: true,
                iconCls: 'o-icon-analysis-small',
                resizable: false,
                closable: false,
                items: {
                    xtype: 'form',
                    bodyPadding: 15,
                    fieldDefaults: {
                        labelAlign: 'left',
                        labelWidth: 60
                    },
                    items: [fieldK, fieldAlpha, fieldBeta, fieldGamma, fieldIterations],
                    buttons: [progressBar, cancelButton, startButton]
                }
            }).show();
        }

        // Do HLDA analysis
        function doHLDAAnalysis(tabPanel, logName) {
           
            var fieldIterations = Ext.create('Ext.form.field.Number', {
                anchor: '100%',
                name: 'iterations',
                fieldLabel: 'Iterations',
                value: 1000,
                maxValue: 100000,
                minValue: 10,
                step: 50,
                keyNavEnabled: true,
                mouseWheelEnabled: true,
                allowBlank: false,
                allowDecimal: false
            });
            var progressBar = Ext.create('Ext.ProgressBar', {
                width: 160
            });
            var task;
            var startButton = Ext.create('Ext.button.Button', {
                text: 'Start',
                handler: function () {
                    if (!fieldIterations.isValid()) {
                        alert('Invalid parameters');
                        return;
                    }
                    fieldIterations.disable();
                    this.disable();

                    Ext.Ajax.request({
                        url: 'Servlet.ashx',
                        params: {
                            action: 'HLDAAnalysis',
                            logName: logName,                           
                            iterations: fieldIterations.getValue()
                        },
                        success: function (response) {
                            task = {
                                run: function () {
                                    Ext.Ajax.request({
                                        url: 'Servlet.ashx',
                                        params: {
                                            action: 'QueryHLDAAnalysisProgress',
                                            logName: logName
                                        },
                                        success: function (response) {
                                            var data = eval('(' + response.responseText + ')');
                                            if (data) {
                                                if (data.state == 'Completed') {
                                                    Ext.TaskManager.stop(task);
                                                    operateWnd.close();
                                                    addHLDAAnalysisTab(tabPanel, logName);
                                                }
                                                else if (data.state == 'Failed') {
                                                    Ext.TaskManager.stop(task);
                                                    progressBar.updateProgress(0.0, data.msg);
                                                }
                                                else { // May be 'Ready', 'Updating'
                                                    progressBar.updateProgress(data.progress, data.msg);
                                                }
                                            }
                                        }
                                    });
                                },
                                interval: 500 // 500ms
                            };
                            Ext.TaskManager.start(task);
                        }
                    });
                }
            });
            var cancelButton = Ext.create('Ext.button.Button', {
                text: 'cancel',
                handler: function () {
                    operateWnd.close();
                    if (startButton.disabled) {
                        Ext.TaskManager.stop(task);
                        Ext.Ajax.request({
                            url: 'Servlet.ashx',
                            params: {
                                action: 'CancelHLDAAnalysis',
                                logName: logName
                            }
                        });
                    }
                }
            });
            var operateWnd = Ext.create('Ext.window.Window', {
                title: 'HLDA Analysis',
                width: 350,
                height: 250,
                layout: 'fit',
                modal: true,
                iconCls: 'o-icon-analysis-small',
                resizable: false,
                closable: false,
                items: {
                    xtype: 'form',
                    bodyPadding: 15,
                    fieldDefaults: {
                        labelAlign: 'left',
                        labelWidth: 60
                    },
                    items: [fieldIterations],
                    buttons: [progressBar, cancelButton, startButton]
                }
            }).show();
        }
        // Add a cpm analysis tab
        function addCPMAnalysisTab(tabPanel, logName) {

            var loadDocTopicGridFinished = false;
            var loadTopicsFinished = false;
            var addCPMPanelsFinished = true;
            var cpmTabMaskRemoved = false;
            var cpmResultTab = Ext.create('Ext.panel.Panel', {
                title: 'CPM Analysis',
                id: 'cpmTab',
                closable: true,
                autoScroll: true,
                loadMask: true,
                bodyPadding: 10,
                iconCls: 'o-icon-analysis-small'
            });
            tabPanel.add(cpmResultTab);
            tabPanel.setActiveTab(cpmResultTab);
            cpmResultTab.body.mask('Loading CPM analysis result...');
            var checkLoadingFinished = function () {
                if (loadDocTopicGridFinished && loadTopicsFinished && addCPMPanelsFinished && !cpmTabMaskRemoved) {
                    cpmResultTab.body.unmask();
                    cpmTabMaskRemoved = true;
                }
            }

            Ext.Ajax.request({
                url: 'Servlet.ashx',
                params: {
                    action: 'GetCPMAnalysisSummary',
                    logName: logName
                },
                success: function (response) {
                    var result = eval('(' + response.responseText + ')');
                    // Create summary form
                    var count = result.data.length;
                    var fields = new Array(count);
                    for (var i = 0; i < count; i++) {
                        fields[i] = Ext.create('Ext.form.field.Display', {
                            fieldLabel: result.data[i][0],
                            value: result.data[i][1]
                        });
                    }
                    var summaryForm = Ext.create('Ext.form.Panel', {
                        bodyPadding: 10,
                        width: 1000,
                        collapsible: true,
                        fieldDefaults: {
                            labelAlign: 'left',
                            labelWidth: 120
                        },
                        margin: '0 0 15 0',
                        title: 'Summary',
                        items: fields
                    });

                    // Create document-topic association panel (HBox)
                    var pageSize = 20;
                    var docStore = Ext.create('Ext.data.Store', {
                        storeId: 'docStore',
                        autoLoad: {
                            start: 0,
                            limit: pageSize
                        },
                        proxy: {
                            type: 'ajax',
                            url: 'servlet.ashx?action=GetCPMDocData&logName=' + logName,
                            reader: {
                                type: 'json',
                                root: 'items',
                                totalProperty: 'total'
                            }
                        },
                        pageSize: pageSize,
                        fields: [
                            { name: 'pid', type: 'string' }
                        ],
                        listeners: {
                            load: function () {
                                loadDocTopicGridFinished = true;
                                checkLoadingFinished();
                            }
                        }
                    });
                    var docGridPanel = Ext.create('Ext.grid.Panel', {
                        store: docStore,
                        width: 390,
                        margin: '0 10 0 0',
                        maxHeight: 450,
                        dockedItems: [{
                            xtype: 'pagingtoolbar',
                            store: docStore,
                            dock: 'bottom',
                            displayInfo: true
                        }],
                        loadMask: true,
                        columns: [
                            { xtype: 'rownumberer', align: 'center' },
                            { text: 'PID', dataIndex: 'pid', width: 345, align: 'center' }
                        ],
                        listeners: {
                            select: function (view, record, index, eOpts) {
                                onCPMDocRowSelect(record.data.pid, logName);
                            }
                        }
                    });
                    var docTopicStore = Ext.create('Ext.data.Store', {
                        storeId: 'cpmDocTopicStore_' + logName,
                        autoLoad: false,
                        fields: [
                            { name: 'topicNo', type: 'string' },
                            { name: 'probability', type: 'float' }
                        ]
                    });
                    var docTopicChart = Ext.create('Ext.chart.Chart', {
                        xtype: 'chart',
                        width: 500,
                        height: 350,
                        animate: true,
                        store: docTopicStore,
                        shadow: true,
                        legend: {
                            position: 'right'
                        },
                        insetPadding: 20,
                        theme: 'Base:gradients',
                        series: [{
                            type: 'pie',
                            angleField: 'probability',
                            showInLegend: true,
                            tips: {
                                trackMouse: true,
                                width: 140,
                                height: 28,
                                renderer: function (storeItem, item) {
                                    // calculate and display percentage on hover
                                    var total = 0;
                                    docTopicStore.each(function (rec) {
                                        total += rec.get('probability');
                                    });
                                    this.setTitle(storeItem.get('topicNo') + ': ' + Math.round(storeItem.get('probability') / total * 100) + '%');
                                }
                            },
                            highlight: {
                                segment: {
                                    margin: 20
                                }
                            },
                            label: {
                                field: 'topicNo',
                                display: 'rotate',
                                contrast: true,
                                font: '18px Arial'
                            }
                        }]
                    });
                    var docHBox = Ext.create('Ext.panel.Panel', {
                        width: 1000,
                        height: 300,
                        collapsible: true,
                        margin: '0 0 10 0',
                        title: 'Patient Trace-CP Pattern Association (Click the grid row to view probabilitie of topics)',
                        layout: {
                            type: 'hbox',
                            align: 'stretch'
                        },
                        items: [docGridPanel, docTopicChart]
                    });
                    var topicVBox = Ext.create('Ext.panel.Panel', {
                        width: 1000,
                        autoScroll: true,
                        collapsible: true,
                        margins: '0 0 10 0',
                        title: 'CP Patterns',
                        bodyPadding: 5,
                        layout: {
                            type: 'vbox',
                            align: 'stretch'
                        }
                    });
                    Ext.Ajax.request({
                        type: 'ajax',
                        url: 'Servlet.ashx',
                        params: {
                            action: 'GetCPMTopicData',
                            logName: logName
                        },
                        success: function (response) {
                            var result = eval('(' + response.responseText + ')');
                            var length = result.items.length;
                            for (var i = 0; i < length; i++) {
                                var store = Ext.create('Ext.data.Store', {
                                    fields: [
                                        { name: 'name', type: 'string' },
                                        { name: 'prob', type: 'float' }
                                    ],
                                    data: result.items[i].actions
                                });
                                var grid = Ext.create('Ext.grid.Panel', {
                                    store: store,
                                    width: 550,
                                    maxHeight: 300,
                                    columns: [
                                        { xtype: 'rownumberer', width: 30, align: 'center' },
                                        { text: 'Action Name', dataIndex: 'name', width: 395, align: 'left' },
                                        { xtype: 'numbercolumn', text: 'Probability', dataIndex: 'prob', align: 'center', format: '0.0000' }
                                    ]
                                });
                                var graphTip = Ext.create('Ext.panel.Panel', {
                                    bodyPadding: 50,
                                    width: 450,
                                    maxHeight: 300,
                                    html: '<p class="graph-shower">Click <a style="font-size: 25px;" href="javascript:onShowCPMPatternGraph(\'' + logName + '\', \'' + i.toString() + '\');">here</a> to show action-timestamp association graph in new window.</p>'
                                });
                                topicVBox.add(Ext.create('Ext.panel.Panel', {
                                    title: 'CP Pattern ' + (i + 1).toString() + ' - Probability: ' + result.items[i].prob.toString(),
                                    margins: '0 0 10 0',
                                    collapsible: true,
                                    layout: {
                                        type: 'hbox',
                                        align: 'stretch'
                                    },
                                    items: [grid, graphTip]
                                }));
                            }
                            loadTopicsFinished = true;
                            checkLoadingFinished();
                        }
                    });

                    // Add the cpm result panels to cpm tab
                    addCPMPanelsFinished = true;
                    cpmResultTab.add(summaryForm);
                    cpmResultTab.add(docHBox);
                    cpmResultTab.add(topicVBox);
                    checkLoadingFinished();
                }
            });
        }

        // Add a hlda analysis tab
        function addHLDAAnalysisTab(tabPanel, logName) 
        {
            var loadDocTopicGridFinished = false;
            var loadTopicsFinished = false;
            var addHLDAPanelsFinished = true;
            var hldaTabMaskRemoved = false;
            var hldaResultTab = Ext.create('Ext.panel.Panel', 
            {
                title: 'HLDA Analysis',
                id: 'hldaTab',
                closable: true,
                autoScroll: true,
                loadMask: true,
                bodyPadding: 10,
                iconCls: 'o-icon-analysis-small'
            });
            tabPanel.add(hldaResultTab);
            tabPanel.setActiveTab(hldaResultTab);
            hldaResultTab.body.mask('Loading HLDA analysis result...');
            var checkLoadingFinished = function ()
            {
                 if (loadDocTopicGridFinished && loadTopicsFinished && addHLDAPanelsFinished && !hldaTabMaskRemoved) 
                {
                    hldaResultTab.body.unmask();
                    hldaTabMaskRemoved = true;
                }
            }

            Ext.Ajax.request(
            {
                url: 'Servlet.ashx',
                params: 
                {
                    action: 'GetHLDAAnalysisSummary',
                    logName: logName
                },
                success: function (response) 
                {
                    var result = eval('(' + response.responseText + ')');
                    // Create summary form
                    var count = result.data.length;
                    var fields = new Array(count);
                    for (var i = 0; i < count; i++) 
                    {
                        fields[i] = Ext.create('Ext.form.field.Display', 
                        {
                            fieldLabel: result.data[i][0],
                            value: result.data[i][1]
                        });
                    }
                    var summaryForm = Ext.create('Ext.form.Panel', 
                    {
                        bodyPadding: 10,
                        width: 1000,
                        collapsible: true,
                        fieldDefaults: 
                        {
                            labelAlign: 'left',
                            labelWidth: 120
                        },
                        margin: '0 0 15 0',
                        title: 'Summary',
                        items: fields
                    });

                    // Create document-topic association panel (HBox)
                    var pageSize = 20;
                    var docStore = Ext.create('Ext.data.Store', 
                    {
                        storeId: 'docStore',
                        autoLoad: 
                        {
                            start: 0,
                            limit: pageSize
                        },
                        proxy: 
                        {
                            type: 'ajax',
                            url: 'servlet.ashx?action=GetHLDADocData&logName=' + logName,
                            reader: 
                            {
                                type: 'json',
                                root: 'items',
                                totalProperty: 'total'
                            }
                        },
                        pageSize: pageSize,
                        fields: 
                        [
                            { name: 'pid', type: 'string' }
                        ],
                        listeners: 
                        {
                            load: function () 
                            {
                                loadDocTopicGridFinished = true;
                                checkLoadingFinished();
                            }
                        }
                    });
                    var docGridPanel = Ext.create('Ext.grid.Panel', 
                    {
                        store: docStore,
                        width: 390,
                        margin: '0 10 0 0',
                        maxHeight: 450,
                        dockedItems: 
                        [{
                            xtype: 'pagingtoolbar',
                            store: docStore,
                            dock: 'bottom',
                            displayInfo: true
                        }],
                        loadMask: true,
                        columns:
                        [
                            { xtype: 'rownumberer', align: 'center' },
                            { text: 'PID', dataIndex: 'pid', width: 345, align: 'center' }
                        ],
                        listeners:
                        {
                            select: function (view, record, index, eOpts)
                            {
                                onHLDADocRowSelect(record.data.pid, logName);
                            }
                        }
                    });
                    var docTopicStore = Ext.create('Ext.data.Store', 
                    {
                        storeId: 'hldaDocTopicStore_' + logName,
                        autoLoad: false,
                        fields: 
                        [
                            { name: 'topicNo', type: 'string' },
                            { name: 'probability', type: 'float' }
                        ]
                    });
                    var docTopicChart = Ext.create('Ext.chart.Chart', {
                        xtype: 'chart',
                        width: 500,
                        height: 350,
                        animate: true,
                        store: docTopicStore,
                        shadow: true,
                        legend: {
                            position: 'right'
                        },
                        insetPadding: 20,
                        theme: 'Base:gradients',
                        series: [{
                            type: 'pie',
                            angleField: 'probability',
                            showInLegend: true,
                            tips: {
                                trackMouse: true,
                                width: 140,
                                height: 28,
                                renderer: function (storeItem, item) {
                                    // calculate and display percentage on hover
                                    var total = 0;
                                    docTopicStore.each(function (rec) {
                                        total += rec.get('probability');
                                    });
                                    this.setTitle(storeItem.get('topicNo') + ': ' + Math.round(storeItem.get('probability') / total * 100) + '%');
                                }
                            },
                            highlight: {
                                segment: {
                                    margin: 20
                                }
                            },
                            label: {
                                field: 'topicNo',
                                display: 'rotate',
                                contrast: true,
                                font: '18px Arial'
                            }
                        }]
                    });
                    var docHBox = Ext.create('Ext.panel.Panel', 
                    {
                        width: 1000,
                        height: 300,
                        collapsible: true,
                        margin: '0 0 10 0',
                        title: 'Patient Trace-CP Pattern Association (Click the grid row to view probabilitie of topics)',
                        layout: {
                            type: 'hbox',
                            align: 'stretch'
                        },
                        items: [docGridPanel, docTopicChart]
                    });
                    var topicVBox = Ext.create('Ext.panel.Panel', {
                        width: 1000,
                        autoScroll: true,
                        collapsible: true,
                        margins: '0 0 10 0',
                        title: 'CP Patterns',
                        bodyPadding: 5,
                        layout: {
                            type: 'vbox',
                            align: 'stretch'
                        }
                    });
                    Ext.Ajax.request({
                        type: 'ajax',
                        url: 'Servlet.ashx',
                        params: {
                            action: 'GetHLDATopicData',
                            logName: logName
                        },
                        success: function (response) {
                            var result = eval('(' + response.responseText + ')');
                            var length = result.items.length;
                            for (var i = 0; i < length; i++) {
                                var store = Ext.create('Ext.data.Store', {
                                    fields: [
                                        { name: 'name', type: 'string' },
                                        { name: 'prob', type: 'float' }
                                    ],
                                    data: result.items[i].actions
                                });
                                var grid = Ext.create('Ext.grid.Panel', {
                                    store: store,
                                    width: 550,
                                    maxHeight: 300,
                                    columns: [
                                        { xtype: 'rownumberer', width: 30, align: 'center' },
                                        { text: 'Action Name', dataIndex: 'name', width: 395, align: 'left' },
                                        { xtype: 'numbercolumn', text: 'Probability', dataIndex: 'prob', align: 'center', format: '0.0000' }
                                    ]
                                });
                                var graphTip = Ext.create('Ext.panel.Panel', {
                                    bodyPadding: 50,
                                    width: 450,
                                    maxHeight: 300,
                                    html: '<p class="graph-shower">Click <a style="font-size: 25px;" href="javascript:onShowHLDAPatternGraph(\'' + logName + '\', \'' + i.toString() + '\');">here</a> to show action-timestamp association graph in new window.</p>'
                                });
                                topicVBox.add(Ext.create('Ext.panel.Panel', {
                                    title: 'CP Pattern ' + result.items[i].name + ' - Probability: ' + result.items[i].prob.toString(),
                                    margins: '0 0 10 0',
                                    collapsible: true,
                                    layout: {
                                        type: 'hbox',
                                        align: 'stretch'
                                    },
                                    items: [grid, graphTip]
                                }));
                            }
                            loadTopicsFinished = true;
                            checkLoadingFinished();
                        }
                    });

                    // Add the cpm result panels to cpm tab
                    addHLDAPanelsFinished = true;
                    hldaResultTab.add(summaryForm);
                    hldaResultTab.add(docHBox);
                    hldaResultTab.add(topicVBox);
                    checkLoadingFinished();
                }
            });
        }

        // Show document-topic association
        function onHLDADocRowSelect(pid, logName) {
            var store = Ext.data.StoreManager.lookup('hldaDocTopicStore_' + logName);
            if (store) {
                store.setProxy({
                    type: 'ajax',
                    url: 'Servlet.ashx?action=GetHLDADocTopicProbability&logName=' + logName + '&pid=' + pid
                });
                store.reload();
            }
        };

        // Show document-topic association
        function onCPMDocRowSelect(pid, logName) {
            var store = Ext.data.StoreManager.lookup('cpmDocTopicStore_' + logName);
            if (store) {
                store.setProxy({
                    type: 'ajax',
                    url: 'Servlet.ashx?action=GetCPMDocTopicProbability&logName=' + logName + '&pid=' + pid
                });
                store.reload();
            }
        };

        // Do HDP analysis
        function doHDPAnalysis(tabPanel, logName) {
           
            var fieldIterations = Ext.create('Ext.form.field.Number', {
                anchor: '100%',
                name: 'iterations',
                fieldLabel: 'Iterations',
                value: 1000,
                maxValue: 100000,
                minValue: 100,
                step: 50,
                keyNavEnabled: true,
                mouseWheelEnabled: true,
                allowBlank: false,
                allowDecimal: false
            });
            var progressBar = Ext.create('Ext.ProgressBar', {
                width: 160
            });
            var task;
            var startButton = Ext.create('Ext.button.Button', {
                text: 'Start',
                handler: function () {
                    if (!(fieldIterations.isValid())) {
                        alert('Invalid parameters');
                        return;
                    }
              
                    fieldIterations.disable();
                    this.disable();

                    Ext.Ajax.request({
                        url: 'Servlet.ashx',
                        params: {
                            action: 'HDPAnalysis',
                            logName: logName,                         
                            iterations: fieldIterations.getValue()
                        },
                        success: function (response) {
                            task = {
                                run: function () {
                                    Ext.Ajax.request({
                                        url: 'Servlet.ashx',
                                        params: {
                                            action: 'QueryHDPAnalysisProgress',
                                            logName: logName
                                        },
                                        success: function (response) {
                                            var data = eval('(' + response.responseText + ')');
                                            if (data) {
                                                if (data.state == 'Completed') 
                                                {
                                                    Ext.TaskManager.stop(task);
                                                    operateWnd.close();
                                                    addHDPAnalysisTab(tabPanel, logName);
                                                }
                                                else if (data.state == 'Failed') 
                                                {
                                                    Ext.TaskManager.stop(task);
                                                    progressBar.updateProgress(0.0, data.msg);
                                                }
                                                else { // May be 'Ready', 'Updating'
                                                    progressBar.updateProgress(data.progress, data.msg);
                                                }
                                            }
                                        }
                                    });
                                },
                                interval: 500 // 500ms
                            };
                            Ext.TaskManager.start(task);
                        }
                    });
                }
            });
            var cancelButton = Ext.create('Ext.button.Button', {
                text: 'cancel',
                handler: function () {
                    operateWnd.close();
                    if (startButton.disabled) {
                        Ext.TaskManager.stop(task);
                        Ext.Ajax.request({
                            url: 'Servlet.ashx',
                            params: {
                                action: 'CancelHDPAnalysis',
                                logName: logName
                            }
                        });
                    }
                }
            });
            var operateWnd = Ext.create('Ext.window.Window', {
                title: 'HDP Analysis',
                width: 350,
                height: 220,
                layout: 'fit',
                modal: true,
                iconCls: 'o-icon-analysis-small',
                resizable: false,
                closable: false,
                items: {
                    xtype: 'form',
                    bodyPadding: 15,
                    fieldDefaults: {
                        labelAlign: 'left',
                        labelWidth: 60
                    },
                    items: [ fieldIterations],
                    buttons: [progressBar, cancelButton, startButton]
                }
            }).show();
        }

        function addHDPAnalysisTab(tabPanel, logName) {

            var loadDocTopicGridFinished = false;
            var loadTopicsFinished = false;
            var addHDPPanelsFinished = true;
            var hdpTabMaskRemoved = false;
            var hdpResultTab = Ext.create('Ext.panel.Panel', {
                title: 'HDP Analysis',
                id: 'hdpTab',
                closable: true,
                autoScroll: true,
                loadMask: true,
                bodyPadding: 10,
                iconCls: 'o-icon-analysis-small'
            });
            tabPanel.add(hdpResultTab);
            tabPanel.setActiveTab(hdpResultTab);
            hdpResultTab.body.mask('Loading HDP analysis result...');
            var checkLoadingFinished = function () {
                if (loadDocTopicGridFinished && loadTopicsFinished && addHDPPanelsFinished && !hdpTabMaskRemoved) {
                    hdpResultTab.body.unmask();
                    hdpTabMaskRemoved = true;
                }
            }

            Ext.Ajax.request({
                url: 'Servlet.ashx',
                params: {
                    action: 'GetHDPAnalysisSummary',
                    logName: logName
                },
                success: function (response) {
                    var result = eval('(' + response.responseText + ')');
                    // Create summary form
                    var count = result.data.length;
                    var fields = new Array(count);
                    for (var i = 0; i < count; i++) {
                        fields[i] = Ext.create('Ext.form.field.Display', {
                            fieldLabel: result.data[i][0],
                            value: result.data[i][1]
                        });
                    }
                    var summaryForm = Ext.create('Ext.form.Panel', {
                        bodyPadding: 10,
                        width: 1000,
                        collapsible: true,
                        fieldDefaults: {
                            labelAlign: 'left',
                            labelWidth: 120
                        },
                        margin: '0 0 15 0',
                        title: 'Summary',
                        items: fields
                    });

                    // Create document-topic association panel (HBox)
                    var pageSize = 20;
                    var docStore = Ext.create('Ext.data.Store', {
                        storeId: 'docStore',
                        autoLoad: {
                            start: 0,
                            limit: pageSize
                        },
                        proxy: {
                            type: 'ajax',
                            url: 'servlet.ashx?action=GetHDPDocData&logName=' + logName,
                            reader: {
                                type: 'json',
                                root: 'items',
                                totalProperty: 'total'
                            }
                        },
                        pageSize: pageSize,
                        fields: [
                            { name: 'pid', type: 'string' }
                        ],
                        listeners: {
                            load: function () {
                                loadDocTopicGridFinished = true;
                                checkLoadingFinished();
                            }
                        }
                    });
                    var docGridPanel = Ext.create('Ext.grid.Panel', {
                        store: docStore,
                        width: 390,
                        margin: '0 10 0 0',
                        maxHeight: 450,
                        dockedItems: [{
                            xtype: 'pagingtoolbar',
                            store: docStore,
                            dock: 'bottom',
                            displayInfo: true
                        }],
                        loadMask: true,
                        columns: [
                            { xtype: 'rownumberer', align: 'center' },
                            { text: 'PID', dataIndex: 'pid', width: 345, align: 'center' }
                        ],
                        listeners: {
                            select: function (view, record, index, eOpts) {
                                onHDPDocRowSelect(record.data.pid, logName);
                            }
                        }
                    });
                    var docTopicStore = Ext.create('Ext.data.Store', {
                        storeId: 'hdpDocTopicStore_' + logName,
                        autoLoad: false,
                        fields: [
                            { name: 'topicNo', type: 'string' },
                            { name: 'probability', type: 'float' }
                        ]
                    });
                    var docTopicChart = Ext.create('Ext.chart.Chart', {
                        xtype: 'chart',
                        width: 500,
                        height: 350,
                        animate: true,
                        store: docTopicStore,
                        shadow: true,
                        legend: {
                            position: 'right'
                        },
                        insetPadding: 20,
                        theme: 'Base:gradients',
                        series: [{
                            type: 'pie',
                            angleField: 'probability',
                            showInLegend: true,
                            tips: {
                                trackMouse: true,
                                width: 140,
                                height: 28,
                                renderer: function (storeItem, item) {
                                    // calculate and display percentage on hover
                                    var total = 0;
                                    docTopicStore.each(function (rec) {
                                        total += rec.get('probability');
                                    });
                                    this.setTitle(storeItem.get('topicNo') + ': ' + Math.round(storeItem.get('probability') / total * 100) + '%');
                                }
                            },
                            highlight: {
                                segment: {
                                    margin: 20
                                }
                            },
                            label: {
                                field: 'topicNo',
                                display: 'rotate',
                                contrast: true,
                                font: '18px Arial'
                            }
                        }]
                    });
                    var docHBox = Ext.create('Ext.panel.Panel', {
                        width: 1000,
                        height: 300,
                        collapsible: true,
                        margin: '0 0 10 0',
                        title: 'Patient Trace-CP Pattern Association (Click the grid row to view probabilitie of topics)',
                        layout: {
                            type: 'hbox',
                            align: 'stretch'
                        },
                        items: [docGridPanel, docTopicChart]
                    });
                    var topicVBox = Ext.create('Ext.panel.Panel', {
                        width: 1000,
                        autoScroll: true,
                        collapsible: true,
                        margins: '0 0 10 0',
                        title: 'CP Patterns',
                        bodyPadding: 5,
                        layout: {
                            type: 'vbox',
                            align: 'stretch'
                        }
                    });
                    Ext.Ajax.request({
                        type: 'ajax',
                        url: 'Servlet.ashx',
                        params: {
                            action: 'GetHDPTopicData',
                            logName: logName
                        },
                        success: function (response) {
                            var result = eval('(' + response.responseText + ')');
                            var length = result.items.length;
                            for (var i = 0; i < length; i++) {
                                var store = Ext.create('Ext.data.Store', {
                                    fields: [
                                        { name: 'name', type: 'string' },
                                        { name: 'prob', type: 'float' }
                                    ],
                                    data: result.items[i].actions
                                });
                                var grid = Ext.create('Ext.grid.Panel', {
                                    store: store,
                                    width: 550,
                                    maxHeight: 300,
                                    columns: [
                                        { xtype: 'rownumberer', width: 30, align: 'center' },
                                        { text: 'Action Name', dataIndex: 'name', width: 395, align: 'left' },
                                        { xtype: 'numbercolumn', text: 'Probability', dataIndex: 'prob', align: 'center', format: '0.0000' }
                                    ]
                                });
                                var graphTip = Ext.create('Ext.panel.Panel', {
                                    bodyPadding: 50,
                                    width: 450,
                                    maxHeight: 300,
                                    html: '<p class="graph-shower">Click <a style="font-size: 25px;" href="javascript:onShowHDPPatternGraph(\'' + logName + '\', \'' + i.toString() + '\');">here</a> to show action-timestamp association graph in new window.</p>'
                                });
                                topicVBox.add(Ext.create('Ext.panel.Panel', {
                                    title: 'CP Pattern ' + (i + 1).toString() + ' - Probability: ' + result.items[i].prob.toString(),
                                    margins: '0 0 10 0',
                                    collapsible: true,
                                    layout: {
                                        type: 'hbox',
                                        align: 'stretch'
                                    },
                                    items: [grid, graphTip]
                                }));
                            }
                            loadTopicsFinished = true;
                            checkLoadingFinished();
                        }
                    });

                    // Add the cpm result panels to cpm tab
                    addHDPPanelsFinished = true;
                    hdpResultTab.add(summaryForm);
                    hdpResultTab.add(docHBox);
                    hdpResultTab.add(topicVBox);
                    checkLoadingFinished();
                }
            });
        }

        // Show document-topic association
        function onHDPDocRowSelect(pid, logName) {
            var store = Ext.data.StoreManager.lookup('hdpDocTopicStore_' + logName);
            if (store) {
                store.setProxy({
                    type: 'ajax',
                    url: 'Servlet.ashx?action=GetHDPDocTopicProbability&logName=' + logName + '&pid=' + pid
                });
                store.reload();
            }
        };

        // Show CPM topic-timestamp pattern graph
        function onShowCPMPatternGraph(logName, index) {
            window.open('CPMPatternGraph.aspx?logName=' + logName + '&index=' + index);
        }

        // Show HLDA topic-timestamp pattern graph
        function onShowHLDAPatternGraph(logName, index) {
            window.open('HLDAPatternGraph.aspx?logName=' + logName + '&index=' + index);
        }

        // Show HDP topic-timestamp pattern graph
        function onShowHDPPatternGraph(logName, index) {
            window.open('HDPPatternGraph.aspx?logName=' + logName + '&index=' + index);
        }

        // Do Testing Analysis Speed
        function doTestAnalysisSpeed(tabPanel, logName) {
            var fieldParts = Ext.create('Ext.form.field.Number', {
                anchor: '100%',
                name: 'parts',
                fieldLabel: 'Seprate the log as # parts',
                value: 5,
                maxValue: 20,
                minValue: 1,
                step: 1,
                keyNavEnabled: true,
                mouseWheelEnabled: true,
                allowBlank: false,
                allowDecimal: false
            });
            var fieldDefaultK = Ext.create('Ext.form.field.Number', {
                anchor: '100%',
                name: 'defaultK',
                fieldLabel: 'Set the default topic number as #',
                value: 3,
                maxValue: 10,
                minValue: 1,
                step: 1,
                keyNavEnabled: true,
                mouseWheelEnabled: true,
                allowBlank: false,
                allowDecimal: false
           });
            var lineConfig = {
                xtype: 'box',
                autoEl: {
                    tag: 'div',
                    style: 'line-height:1px; font-size: 1px;margin-bottom:4px',
                    children: [{
                        tag: 'img',
                        src: 'Content/images/pixel.gif',
                        height: '2px',
                        width: '100%'
                    }]
                }
            };
            var fieldTopicNo = Ext.create('Ext.form.field.Number', {
                anchor: '100%',
                name: 'topicNo',
                fieldLabel: 'Set the topic number from 1 to #',
                value: 3,
                maxValue: 10,
                minValue: 1,
                step: 1,
                keyNavEnabled: true,
                mouseWheelEnabled: true,
                allowBlank: false,
                allowDecimal: false
            });
            var progressBar = Ext.create('Ext.ProgressBar', {
                width: 210
            });
            var task;
            var startButton = Ext.create('Ext.button.Button', {
                text: 'Start',
                handler: function () {
                    if (!(fieldParts.isValid() && fieldDefaultK.isValid() && fieldTopicNo.isValid())) {
                        alert('Invalid parameters');
                        return;
                    }
                    fieldParts.disable();
                    fieldDefaultK.disable();
                    fieldTopicNo.disable();
                    this.disable();

                    Ext.Ajax.request({
                        url: 'Servlet.ashx',
                        params: {
                            action: 'TestAnalysisSpeed',
                            logName: logName,
                            parts: fieldParts.getValue(),
                            defaultK: fieldDefaultK.getValue(),
                            topicNo: fieldTopicNo.getValue()
                        },
                        success: function (response) {
                            task = {
                                run: function () {
                                    Ext.Ajax.request({
                                        url: 'Servlet.ashx',
                                        params: {
                                            action: 'QueryTestAnalysisSpeedProgress',
                                            logName: logName
                                        },
                                        success: function (response) {
                                            var data = eval('(' + response.responseText + ')');
                                            if (data) {
                                                if (data.state == 'Completed') {
                                                    Ext.TaskManager.stop(task);
                                                    operateWnd.close();
                                                    addTestAnalysisSpeedTab(tabPanel, logName);
                                                }
                                                else if (data.state == 'Failed') {
                                                    Ext.TaskManager.stop(task);
                                                    progressBar.updateProgress(0.0, data.msg);
                                                }
                                                else { // May be 'Ready', 'Updating'
                                                    progressBar.updateProgress(data.progress, data.msg);
                                                }
                                            }
                                        }
                                    });
                                },
                                interval: 500 // 500ms
                            };
                            Ext.TaskManager.start(task);
                        }
                    });
                }
            });
            var cancelButton = Ext.create('Ext.button.Button', {
                text: 'cancel',
                handler: function () {
                    operateWnd.close();
                    if (startButton.disabled) {
                        Ext.TaskManager.stop(task);
                        Ext.Ajax.request({
                            url: 'Servlet.ashx',
                            params: {
                                action: 'CancelTestAnalysisSpeed',
                                logName: logName
                            }
                        });
                    }
                }
            });
            var operateWnd = Ext.create('Ext.window.Window', {
                title: 'Test Analysis Speed',
                width: 400,
                height: 180,
                layout: 'fit',
                modal: true,
                iconCls: 'o-icon-analysis-small',
                resizable: false,
                closable: false,
                items: {
                    xtype: 'form',
                    bodyPadding: 15,
                    fieldDefaults: {
                        labelAlign: 'left',
                        labelWidth: 200
                    },
                    items: [fieldParts, fieldDefaultK, lineConfig, fieldTopicNo],
                    buttons: [progressBar, cancelButton, startButton]
                }
            }).show();
        }

        // Add a Test Analysis Speed tab
        function addTestAnalysisSpeedTab(tabPanel, logName) {

            var tasResultTab = Ext.create('Ext.panel.Panel', {
                title: 'Testing Analysis Speed',
                id: 'tasTab',
                closable: true,
                autoScroll: true,
                loadMask: true,
                bodyPadding: 10,
                iconCls: 'o-icon-analysis-small'
            });
            tabPanel.add(tasResultTab);
            tabPanel.setActiveTab(tasResultTab);

            var traceCountStore = Ext.create('Ext.data.Store', {
                autoLoad: true,
                proxy: {
                    type: 'ajax',
                    url: 'servlet.ashx?action=GetTestingResultWithTraceCount&logName=' + logName
                },
                fields: [
                    { name: 'traceCount', type: 'int' },
                    { name: 'timeElapsed', type: 'float' }
                ]
            });

            var topicNoStore = Ext.create('Ext.data.Store', {
                autoLoad: true,
                proxy: {
                    type: 'ajax',
                    url: 'servlet.ashx?action=GetTestingResultWithTopicNo&logName=' + logName
                },
                fields: [
                    { name: 'topicNo', type: 'int' },
                    { name: 'timeElapsed', type: 'float' }
                ]
            });

            var traceCountGrid = Ext.create('Ext.grid.Panel', {
                store: traceCountStore,
                margin: '10',
                width: 600,
                magin: '0, 0, 10, 0',
                maxHeight: 450,
                loadMask: true,
                columns: [
                    { xtype: 'rownumberer', width: 30, align: 'center' },
                    { text: 'Number of traces in log', dataIndex: 'traceCount', width: 240, align: 'center' },
                    { text: 'Time Elapsed (ms)', dataIndex: 'timeElapsed', width: 300, align: 'center' }
                ]
            });

            var topicNoGrid = Ext.create('Ext.grid.Panel', {
                store: topicNoStore,
                margin: '10',
                width: 600,
                magin: '0, 0, 10, 0',
                maxHeight: 450,
                loadMask: true,
                columns: [
                    { xtype: 'rownumberer', width: 30, align: 'center' },
                    { text: 'Number of topics', dataIndex: 'topicNo', width: 240, align: 'center' },
                    { text: 'Time Elapsed (ms)', dataIndex: 'timeElapsed', width: 300, align: 'center' }
                ]
            });

            var traceCountChart = Ext.create('Ext.chart.Chart', {
                animate: true,
                width: 600,
                height: 300,
                store: traceCountStore,
                axes: [{
                    type: 'Numeric',
                    position: 'left',
                    fields: ['timeElapsed'],
                    title: 'Time Elapsed (ms)',
                    grid: true,
                    minimum: 0
                }, {
                    type: 'Numeric',
                    position: 'bottom',
                    fields: ['traceCount'],
                    title: 'Number of Traces in log'
                }],
                series: [{
                    type: 'line',
                    highlight: {
                        size: 7,
                        radius: 7
                    },
                    axis: 'left',
                    xField: 'traceCount',
                    yField: 'timeElapsed',
                    markerConfig: {
                        type: 'cross',
                        size: 4,
                        radius: 4,
                        'stroke-width': 0
                    }
                }]
            });

            var topicNoChart = Ext.create('Ext.chart.Chart', {
                animate: true,
                store: topicNoStore,
                width: 600,
                height: 300,
                axes: [{
                    type: 'Numeric',
                    position: 'left',
                    fields: ['timeElapsed'],
                    title: 'Time Elapsed (ms)',
                    grid: true,
                    minimum: 0
                }, {
                    type: 'Numeric',
                    position: 'bottom',
                    fields: ['topicNo'],
                    title: 'Number of Topics',
                    minimum: 1
                }],
                series: [{
                    type: 'line',
                    highlight: {
                        size: 7,
                        radius: 7
                    },
                    axis: 'left',
                    xField: 'topicNo',
                    yField: 'timeElapsed',
                    markerConfig: {
                        type: 'cross',
                        size: 4,
                        radius: 4,
                        'stroke-width': 0
                    }
                }]
            });

            var traceCountPanel = Ext.create('Ext.panel.Panel', {
                width: 620,
                title: 'Time elapsed - trace count',
                margin: '10',
                items: [traceCountGrid, traceCountChart]
            });

            var topicNoPanel = Ext.create('Ext.panel.Panel', {
                width: 620,
                title: 'Time elapsed - topic number',
                margin: '10',
                items: [topicNoGrid, topicNoChart]
            });

            // Add the cpm result panels to cpm tab
            tasResultTab.add(traceCountPanel);
            tasResultTab.add(topicNoPanel);
        }
    </script>
</head>
<body>
    <div id="loadingMask"></div>
</body>
</html>
